﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Transactions;
using System.Web.Http;
using SalesSys.BLL;
using SalesSys.Comm.Utility;
using SalesSys.DAL.Models;
using SalesSys.Service.Sales;
using SalesSys.Site.Models;
using SalesSys.WebCore;
using SalesSys.WebCore.Authorize;
using SalesSys.BLL.Sales;
using SalesSys.BLL.Purchasing;

namespace SalesSys.Site.Controllers.Api
{
    /// <summary>
    /// 驻厂
    /// </summary>
    [RoutePrefix("api/FieldMan")]
    public class FieldManController : BaseApiController
    {
        OrderBLL bll = BllFactory.GetBll<OrderBLL>();
        private IPurchasingBLL purchasingBll = new PurchasingBLL();
        private IDirectSale directSaleSvc = new SalesSvc();
        #region old

        /// <summary>
        /// 获取驻厂订单
        /// </summary>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <param name="state">订单状态</param>
        /// <param name="type">订单类型</param>
        /// <param name="name">供应商名称\客户名称\客户简称</param>
        /// <returns></returns>
        [Route("Order")]
        public ViewDtos<Order> GetOrder(int page, int rows, OrderState? state, OrderType? type, string name = null)
        {
            var empId = ClientHelper.ClientInfo.Id;
            //var paging = GetRequestQuery();
            var re = bll.GetFieldManOrder(empId, page, rows, state, type, name);
            var dto = new ViewDtos<Order>();
            dto.Data = re.Value;
            dto.Total = re.Key;
            dto.Page = page;
            dto.Rows = rows;
            return dto;
        }

        /// <summary>
        /// 驻厂确认订单--库提
        /// </summary>
        /// <param name="orderId">计划单编号</param>
        /// <returns></returns>
        [Route("ConfirmOrder")]
        public IResultState PutConfirmOrder(Guid orderId)
        {
            var empId = ClientHelper.ClientInfo.Id;
            var order = bll.Details(orderId);

            if (order.State != OrderState.Checked)
            {
                return ReState.ArgError.Create("订单状态无效");
            }
            if (order.Provider.MainFieldMan.Id != empId)
            {
                return ReState.ArgError.Create("接单人员错误");
            }

            order.State = OrderState.Ordered;
            order.Records.Add(OrderStateChangeRecord(order));

            bll.Edit(order);
            var str = string.Format("{0:M/d HH:mm} 驻厂人员[{1}]已经成功接单", DateTime.Now, order.Provider.MainFieldMan.Name);
            SendMsg(str, order.Creater.Id);
            return ResultState.CreateSuccess();
        }
        /// <summary>
        /// 驻厂确认订单-直采确认接单
        /// </summary>
        /// <param name="orderId">计划单编号</param>
        /// <returns></returns>
        [Route("OrderPurchasingConfirm")]
        public IResultState PutConfirmOrderPurchasing(Guid orderId)
        {
            var empId = ClientHelper.ClientInfo.Id;
            var order = bll.Details(orderId);

            if (order.State != OrderState.Checked)
            {
                return ReState.ArgError.Create("订单状态无效");
            }
            if (order.Provider.MainFieldMan.Id != empId)
            {
                return ReState.ArgError.Create("接单人员错误");
            }
            var state = directSaleSvc.OrderPurchasingConfirm(ClientHelper.ClientInfo.Id, orderId);
            if (state.State == (int)ReState.Success)
            {
                var str = string.Format("{0:M/d HH:mm} 驻厂人员[{1}]已经成功接单", DateTime.Now, order.Provider.MainFieldMan.Name);
                SendMsg(str, order.Creater.Id);
            }
            return state;
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msg">消息内容</param>
        /// <param name="toCustomerId">接收人编号</param>
        private void SendMsg(string msg, Guid toCustomerId)
        {
            var nb = new NoticeInfoBLL();
            nb.SendMsg(msg, toCustomerId, null);
        }

        /// <summary>
        /// 确认发货
        /// </summary>
        /// <param name="orderId">计划单编号</param>
        /// <returns></returns>
        [Route("ConfirmSend")]
        public IResultState PutConfirmSend(Guid orderId)
        {

            var empId = ClientHelper.ClientInfo.Id;
            var order = bll.Details(orderId);
            if (order.State != OrderState.Ordered)
            {
                return ReState.ArgError.Create("订单状态无效");
            }
            var state = directSaleSvc.OrderSend(empId, orderId);
            if (state.State == (int)ReState.Success)
            {
                var str = string.Format("{0:M/d HH:mm} 驻厂人员[{1}]已经成功发货", DateTime.Now, order.Provider.MainFieldMan.Name);
                SendMsg(str, order.Creater.Id);
            }
            return state;
        }

        /// <summary>
        /// 追加发货信息,并出库
        /// </summary>
        /// <param name="ord">计划单实体</param>
        /// <returns></returns>
        [Route("EditSendInfo")]
        public IResultState PutEditSendInfo(Order ord)
        {
            var order = bll.Details(ord.Id);
            if (order == null || order.State != OrderState.Send)
            {
                return ReState.ArgError.Create("错误的订单信息");
            }
            using (var tran = new TransactionScope())
            {
                directSaleSvc.RealWeight(ord, ClientHelper.ClientInfo);
                directSaleSvc.ToDepotDelivery(ord.Id, ClientHelper.ClientInfo.Id);
                tran.Complete();
            }

            return ReState.Success.Create();
        }


        /// <summary>
        /// 直发计划单，追加发货信息
        /// </summary>
        /// <param name="ord">计划单实体</param>
        /// <returns></returns>
        [Route("EditPurchaseGoods")]
        public IResultState PutEditPurchaseGoods(Order ord)
        {
            var order = bll.Details(ord.Id);

            if (order == null || order.State != OrderState.Send)
            {
                return ReState.ArgError.Create("错误的订单信息");
            }
            var pOrder = purchasingBll.GetPurchaseOrderByOrderId(order.Id);
            if (pOrder == null)
                return ReState.Error.Create("计划单相应采购单不存在");
            if (pOrder.State != SalesSys.DAL.Models.PurchaseOrder.PurchaseState.Send)
                return ReState.Error.Create("对应采购单还未发送");

            using (var tran = new TransactionScope())
            {
                directSaleSvc.RealWeight(ord, ClientHelper.ClientInfo);
                purchasingBll.EditPurchaseOrderGoods(order);
                order.IsToDeliveryList = true;
                bll.Edit(order);
                tran.Complete();
            }

            return ReState.Success.Create();
        }

        private OrderRecord OrderStateChangeRecord(Order order)
        {
            // order.State = OrderState.Send;
            var red = new OrderRecord();
            red.CreateTime = DateTime.Now;
            red.DiscountType = DiscountType.StateChange;
            red.Tag = ((int)order.State) + "";
            red.LinkId = order.Id + "";
            red.Remarks = "订单状态变化:" + order.State.GetDescInfo() + ",操作人：" + ClientHelper.ClientInfo.Name;
            return red;
        }

        #endregion

    }
}
